<template>
  <view class="video-item">
    <video
      id="myVideo"
      :src="videoInfo.src"
      :style="{ width: winWidth, height: winHeight }"
      loop
      :autoplay="true"
      :controls="false"
      :show-center-play-btn="false"
      :show-progress="true"
      @loadedmetadata="handleLoadedmetadata"
      @timeupdate="handleTimeUpdate"
    ></video>
    <view class="video-info" @click.stop="handleVideoClicked">
      <image v-show="!isPlaying" class="btn-play" :src="playImg"></image>
      <view class="info-text" @click.stop>
        <view class="author" @click="handleAuthorClick">
          <image class="avatar" :src="videoInfo.personPic"></image>
          <view class="author-name u-line-1">{{ videoInfo.ownName }}</view>
          <view v-if="showFollow" 
            :class="['follow', { followed: videoInfo.isFocusUser }]"
            @click.stop="handleFollow"
          >
            {{ videoInfo.isFocusUser ? "已关注" : "关注" }}
          </view>
        </view>
        <view class="info-content" :class="{ 'u-line-2': !showAllContent }">
          {{ content || "" }}
          <view
            v-if="isShowReadMore"
            class="unfold"
            @click="showAllContent = !showAllContent"
            >{{ showAllContent ? "收起" : "展开" }}
          </view>
        </view>
        <view class="c-time">
          {{ videoInfo.ctime || "" }}
        </view>
      </view>
      <view class="player-progress" @click.stop>
        <u-slider
          v-model="progress"
          height="8"
          block-width="12"
          inactive-color="#413f40"
          active-color="#ffffff"
          @end="onProgressEnd"
          @start="onStart"
          @click.native="onProgressClick"
        ></u-slider>
      </view>
      <view class="action" @click.stop>
        <view class="action-item" @click="handlePraise('点赞')">
          <text v-if="videoInfo.isPraise == 1" class="icon icon-like-on"></text>
          <text v-else class="icon icon-like"></text>
          <view>{{ videoInfo.likeCnt || 0 }}</view>
        </view>

        <view v-if="showComment" class="action-item" @click="handleComment">
          <text class="icon icon-comment"></text>
          <view>{{ videoInfo.commentCount || 0 }}</view>
        </view>

        <view v-if="showCollect" class="action-item" @click="handleCollect">
          <text
            v-if="videoInfo.isFavorite == 1"
            class="icon icon-collect-on"
          ></text>
          <text v-else class="icon icon-collect"></text>
          <view>{{ videoInfo.cCnt || 0 }}</view>
        </view>

        <view class="action-item">
          <button 
            :data-title="videoInfo.title"
            :data-articleid="videoInfo.articleId"
            :data-thumb="videoInfo.info"
            data-sharetype="2" 
            plain
            size="mini" 
            class="btn-share" 
            open-type="share">
            <text class="icon icon-zhuanfa"></text>
          </button>
          <view>{{ videoInfo.shareCount || 0 }}</view>
        </view>
      </view>
    </view>

    <LoginDialog ref="loginDialog" @loginSuccessBack="loginSuccessBack"></LoginDialog>
  </view>
</template>

<script>
import { addArticlePraise, addShortVideoFavorite } from "@/api/modules/career";
import debounce from 'lodash/debounce';
import LoginDialog from "@/components/LoginDialog";
export default {
  props: {
    videoInfo: {
      type: Object,
      default: function () {
        return {};
      },
    },
    showComment: {
      type: Boolean,
      default: true,
    },
    showCollect: {
      type: Boolean,
      default: true,
    },
    showFollow: {
      type: Boolean,
      default: true,
    },
  },
  components:{
    LoginDialog
  },
  data() {
    return {
      personId: uni.getStorageSync("person-id").slice(2) || "",
      playImg: this.$imgBaseSelf + "career/icon-play.png",
      isPlaying: true,
      // 屏幕宽高
      winWidth: "",
      winHeight: "",
      navHeight: getApp().globalData.navHeight,
      showAllContent: false,
      isShowReadMore: false,
      progress: 0,
      duration: 0,
      isDrag: false,
      clickNum: 0,
      clickTimer: null,
      moduleType: "VIDEO",
      articleId: this.videoInfo.articleId,
    };
  },
  watch: {
    // current: {
    //   immediate: true,
    //   handler: function () {
    //     this.video = uni.createVideoContext("myVideo", this);
    //     this.$nextTick(() => {
    //       if (this.current != this.videoIndex) {
    //         this.stopPlay();
    //       } else {
    //         this.playVideo();
    //       }
    //     });
    //   },
    // },
    videoInfo: {
      immediate: true,
      handler: function (nVal, oVal) {
        this.isPraise = nVal.isPraise;
        this.isFavorite = nVal.isFavorite;
        this.articleId = nVal.articleId;
      },
    },
  },
  computed: {
    content() {
      if (this.videoInfo.content && this.videoInfo.content.length > 30) {
        this.isShowReadMore = true;
        if (this.showAllContent) {
          return this.videoInfo.content;
        }
        return this.videoInfo.content.slice(0, 30) + "...";
      }
      return this.videoInfo.content;
    },
  },
  created() {
    let wW = uni.getSystemInfoSync().windowWidth;
    let wH = uni.getSystemInfoSync().windowHeight;
    this.winWidth = `${wW}px`;
    this.winHeight = `${wH}px`;
  },
  mounted() {
    this.video = uni.createVideoContext("myVideo", this);
  },
  methods: {
    // 播放
    playVideo() {
      this.video.play();
      this.isPlaying = true;
    },
    // 暂停
    pauseVideo() {
      this.video.pause();
      this.isPlaying = false;
    },
    onProgressEnd() {
      this.videoSeek(this.progress);
    },
    videoSeek(progress) {
      let seekTime = parseInt((progress / 100) * this.duration);
      this.video.seek(seekTime);
      this.isDrag = false;
    },
    onStart() {
      this.isDrag = true;
    },
    // 播放进度变化时触发
    handleTimeUpdate(e) {
      let { currentTime, duration } = e.detail;
      if (this.isDrag) return;
      this.progress = parseInt((currentTime / duration).toFixed(2) * 100);
    },
    onProgressClick() {
      this.isDrag = true;
      this.videoSeek(this.progress);
    },
    // 点击视频（单击/双击）
    handleVideoClicked() {
      this.clickTimer && clearTimeout(this.clickTimer);
      this.clickNum++;
      this.clickTimer = setTimeout(() => {
        if (this.clickNum >= 2) {
          console.log("你双击了");
          this.handlePraise("点赞");
        } else {
          console.log("你单击了");
          if (this.isPlaying) {
            this.pauseVideo();
          } else {
            this.playVideo();
          }
        }
        this.clickNum = 0;
      }, 250);
    },
    handleComment() {
      if (!this.checkLogin("评论")) return;
      this.$emit("comment");
    },
    handleLoadedmetadata(e) {
      const { duration } = e.detail;
      this.duration = duration;
    },

    handlePraise(text) {
      console.log(text);
      if (!this.checkLogin(text)) return;

      let type = this.videoInfo.isPraise == 1 ? "cancel" : "add";
      let title = this.videoInfo.isPraise == 1 ? "取消成功" : "点赞成功";
      const params = {
        person_id: this.personId,
        article_id: this.articleId,
        type: type,
      };
      addArticlePraise(params).then((res) => {
        console.log("🚀 ~ file: VideoItemVX.vue:258 ~ addArticlePraise ~ res:", res)
        if (res.code == 200) {
          // this.$emit("update", { type, operateType: "praise" });
        }
        // uni.showToast({
        //   title: res.status_desc,
        //   icon: "none",
        // });
      });
      
      this.$emit("update", { type, operateType: "praise" });
      uni.showToast({
        title: title,
        icon: "none",
      });
    },

    // 收藏
    handleCollect() {
      if (!this.checkLogin("收藏")) return;

      let type = this.videoInfo.isFavorite == 1 ? "cancel" : "add";
      const params = {
        person_id: this.personId,
        article_id: this.articleId,
        type: type,
      };
      addShortVideoFavorite(params).then((res) => {
        if (res.code == 200) {
          this.$emit("update", { type, operateType: "favorite" });
        }
        uni.showToast({
          title: res.status_desc,
          icon: "none",
        });
      });
    },

    checkLogin(text = "") {
      if (!this.personId) {
        this.$refs.loginDialog.setVisibility(true);
        return false;
      }
      return true;
    },
    handleAuthorClick() {
      this.$emit("authorClick");
    },
    handleFollow() {
      this.$emit('follow')
    },
    loginSuccessBack(){
      console.log("loginSuccessBack");
      this.personId = uni.getStorageSync("person-id").slice(2) || undefined;
    }
  },
};
</script>

<style lang="scss" scoped>
.video-item {
  height: 100vh;
}
.video-info {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  z-index: 1;
  .icon-back {
    position: absolute;
    top: 108rpx;
    left: 32rpx;
    background-image: url($img-base + "back.png");
    width: 44rpx;
    height: 44rpx;
  }
  .btn-play {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 144rpx;
    height: 172rpx;
    transform: translate(-50%, -50%);
  }

  .info-text {
    position: absolute;
    padding: 0 200rpx 124rpx 32rpx;
    bottom: 0;
    left: 0;
    right: 0;
    background: linear-gradient(180deg, rgba(0,0,0,0) 0%, rgba(0,0,0,0.45) 100%);

    .author {
      margin-bottom: 20rpx;
      display: flex;
      align-items: center;
      .avatar {
        flex-shrink: 0;
        width: 60rpx;
        height: 60rpx;
        margin-right: 18rpx;
        border: 4rpx solid #ffffff;
        border-radius: 50%;
      }
      .author-name {
        font-size: 36rpx;
        font-weight: bold;
        color: #ffffff;
      }
      .follow {
        margin-left: 16rpx;
        padding: 8rpx 20rpx;
        color: #ffffff;
        font-size: 22rpx;
        background: #f04646;
        border-radius: 26rpx;
        white-space: nowrap;
      }
      .followed {
        color: #bfbfbf;
        background: transparent;
        border: 2rpx solid #bfbfbf;
      }
    }

    .info-content {
      position: relative;
      margin-bottom: 14rpx;
      font-size: 30rpx;
      color: #ececec;

      .unfold {
        display: inline;
        margin-left: 8rpx;
        font-size: 32rpx;
        color: #ffffff;
        text-decoration: underline;
      }
    }

    .c-time {
      font-size: 26rpx;
      color: #c3c3c3;
    }
  }
  .action {
    position: absolute;
    bottom: 124rpx;
    right: 32rpx;
    width: 80rpx;
    color: #ffffff;
    margin-bottom: 80rpx;
    
    .action-item {
      margin-bottom: 36rpx;
      text-align: center;
      font-size: 26rpx;
      .icon {
        width: 64rpx;
        height: 64rpx;

        &-zhuanfa {
          background-image: url($img-base + "career/zhuanfa2.png");
        }
        &-comment {
          background-image: url($img-base + "career/comment.png");
        }
        &-like {
          background-image: url($img-base + "career/like2.png");
          &-on {
            background-image: url($img-base + "career/like-on2.png");
          }
        }
        &-collect {
          background-image: url($img-base + "career/star.png");
          &-on {
            background-image: url($img-base + "career/star-on.png");
          }
        }
      }
      .btn-share {
        padding: 0;
        border: none;
      }
    }
  }
  .player-progress {
    position: absolute;
    bottom: 56rpx;
    left: 0;
    right: 0;
  }
}
</style>